<template>
    <el-container v-loading="loading">
        <el-header class="head">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/' }"><el-icon><House /></el-icon></el-breadcrumb-item>
                <el-breadcrumb-item :to="{ path: '/search/none/none/none' }">EcDNA Search</el-breadcrumb-item>
                <el-breadcrumb-item>Detail</el-breadcrumb-item>
                <el-breadcrumb-item>OncotreeLineage: {{ route.params.OncotreeLineage }}</el-breadcrumb-item>
                <el-breadcrumb-item>MajorTumorType: {{ route.params.MajorTumorType }}</el-breadcrumb-item>
                <el-breadcrumb-item v-if="route.params.Cellline != 'none'">Cell Line: {{ route.params.Cellline }}</el-breadcrumb-item>
                <el-breadcrumb-item v-if="route.params.SampleType != 'none'" >SampleType: {{ route.params.SampleType }}</el-breadcrumb-item>
            </el-breadcrumb>
            <div v-if="has_seq_data">
                <el-button
                    class="buttonItem"
                    type="info"
                    style="margin: 20px; background-color: #337ab7; border-color: #2e6da4;" 
                    @click="downloadSeq('zip')"
                    >download all data
                </el-button>
            </div>
        </el-header>
        <el-main>
            <h1>Gene Info</h1>
            <el-table
                :data="tableData"
                style="width: 100%"
                table-layout="auto"
            >
                    <el-table-column prop="Chrom" label="Chrom" />
                    <el-table-column prop="Start" label="Start" />
                    <el-table-column prop="End" label="End"/>
                    <el-table-column prop="Strand" label="Strand"/>
                    <el-table-column prop="AmpliconID" label="AmpliconID"/>
                    <el-table-column prop="Gene" label="Gene" show-overflow-tooltip>
                        <template #default="scope">
                            <span v-if="scope.row.Gene == 'null'"></span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="CancerGene" label="CancerGene" show-overflow-tooltip>
                        <template #default="scope">
                            <span v-if="scope.row.CancerGene == 'null'"></span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="SE" label="SE" show-overflow-tooltip>
                        <template #default="scope">
                            <span v-if="scope.row.CancerGene == 'null'"></span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="Length" label="Length" />
                    <el-table-column prop="SplitCount" label="SplitCount"/>
                    <el-table-column prop="CN" label="CN"/>
            </el-table>
            <el-divider />
                <el-descriptions                
                    direction="vertical"
                    :column="1"
                    border>
                    <template #title><h1>Ring Data</h1></template>
                    <template #extra>
                        <el-button
                            class="buttonItem"
                            type="info"
                            style="margin: 20px; background-color: #337ab7; border-color: #2e6da4;" 
                            @click="downloadSVG"
                            >download image
                        </el-button>
                    </template>
                    <el-descriptions-item >
                        <RingChartV3
                            ref="RingChartContainer"
                            :chromData="chromData"
                            :geneData="geneData"
                            :cnData="cnData"
                            :label_denominator="label_denominator"
                            :spacing="spacing"
                        />
                    </el-descriptions-item>
                </el-descriptions>
                

            <el-divider v-if="showPdf" />
            <el-descriptions
                :column="2"
                size="large"
                border
                v-if="showPdf"
            >   
                <template #title>
                    <h1>Image Info</h1>
                </template>
                <template #extra>
                    <el-button
                        class="buttonItem"
                        type="info"
                        style="margin: 20px; background-color: #337ab7; border-color: #2e6da4;" 
                        @click="downloadSeq('pdf')"
                        >download PDF
                    </el-button>
                </template>
                <el-descriptions-item label="circ img">
                    <vue-office-pdf :src="circPath" />
                </el-descriptions-item>
            </el-descriptions>
            <el-divider />
            <el-descriptions
                direction="vertical"
                :column="1"
                border>
                <template #title>
                    <h1>Junction Sequence Info</h1>
                </template>
                <div v-if="has_seq_data">
                    <div v-for="seq in seqData" :key="seq[0].junctionSeq">
                        <el-descriptions-item >
                            <template #label>
                                <pre>{{ seq[0].junctionSeq }}</pre>
                            </template>
                            <pre>{{ seq[1].junctionSeq }}</pre>
                            <pre>{{ seq[2].junctionSeq }}</pre>
                        </el-descriptions-item>
                    </div>
                </div>
                <div v-else>
                    <el-descriptions-item>
                        <el-empty description="PE support"></el-empty>
                    </el-descriptions-item>
                </div>
            </el-descriptions>
        </el-main>
        <el-footer></el-footer>
    </el-container>
</template>

<script lang="ts" setup name="Detail">
    import { useRoute } from 'vue-router';
    import { onBeforeMount, ref, reactive } from 'vue'
    import { ElMessage } from 'element-plus'
    import { get, post } from '@/axios/api';

    import VueOfficePdf from '@vue-office/pdf'
    import RingChartV3 from './RingChartV3.vue'


    const route = useRoute()
    const baseUrl = import.meta.env.VITE_MEDIA_URL + '/' + 'backend-static/result/' + route.params.filename + "/"
    let has_seq_data = ref(false)
    let cnData: any = ref([])
    let geneData: any = ref([])
    let chromData: any = ref([])

    let tableData = ref([])
    let loading = ref(false)
    let seqData:any = ref([])
    let label_denominator:any = ref(null)
    let spacing:any = ref(null)

    const svgContent:any = ref('')
    const RingChartContainer:any = ref(null)

    const showRingData:any = ref(false)
    const showPdf:any = ref(false)
    
    const circPath = computePdfPath(route.params.filename, route.params.circ)

    function downloadSVG() {
        if (RingChartContainer.value) {
            RingChartContainer.value.downloadPdf()
        }
    }


    function checkPathExists(path: string): Promise<boolean> {
        return fetch(path, { method: 'HEAD' })
            .then(response => response.ok)
            .catch(() => false)
    }

    function computePdfPath(filename:any, circ: any) {
        let path = ''
        if (filename.startsWith('EGA') && filename.endsWith('scatac')) {
            path = baseUrl + filename.split('_')[1] + "_ask_plot_new_v4/circular_" + circ + ".pdf"
        } else {
            path = baseUrl + filename + "_ask_plot_new_v4/circular_" + circ + ".pdf"
        }
        checkPathExists(path).then(exists => {
            if (exists) {
                showPdf.value = true
            } else {
                showPdf.value = false
            }
        })
        return path
    }

    async function getCircData() {
        loading.value = true
        let data = {
            filename: route.params.filename,
            circ: route.params.circ
        }
        try {
            let res:any = await post('/get_circ_data/', data)
            if (res && res.success) {
                if (res.has_circ_data) {
                    res.circ_data.forEach((ele:any) => ele.Length = ele.End - ele.Start + 1)
                    tableData.value = res.circ_data
                    if (res.has_seq_data) {
                        has_seq_data.value = true
                        for (let i in res.seq_data) {
                            seqData.value.push(res.seq_data[i])
                        }
                        tableData.value = res.circ_data
                    } else {
                        has_seq_data.value = false
                    }
                }
                loading.value = false
            } else {
                loading.value = false
                ElMessage({
                    message: res.msg || 'An error occured',
                    type: 'error',
                })
            }
        } catch (error:any) {
            loading.value = false
            ElMessage({
                message: error,
                type: 'error',
            })
        }
    }

    async function getRingData() {
        let params = {
            filename: route.params.filename,
            circ: route.params.circ
        }
        try {
            let res:any = await post('/get_ring_chart_v1/', params)
            if (res && res.success) {
                chromData.value = res.chrom_sunburst
                cnData.value = res.cn_sunburst
                geneData.value = res.gene_sunburst
                label_denominator.value = res.label_denominator
                spacing.value = res.spacing
                showRingData.value = true
            }
            svgContent.value = res
        }  catch (error:any) {
            loading.value = false
            ElMessage({
                message: error,
                type: 'error',
            })
        }
    }

    async function downloadSeq(downloadType: string) {
        loading.value = true
        let data = {
            filename: route.params.filename,
            circ: route.params.circ,
            download_type: downloadType
        }

        try {
            let res:any = await post('/get_seq_data/', data, {
                responseType: 'blob',
                headers:{ 'Content-Type': 'application/json; application/octet-stream'}
            })
            if (res) {
                const blob = new Blob([res],  { type: `application/${downloadType}` })
                let urlObject = window.URL
                let url = urlObject.createObjectURL(blob)
                let ele = document.createElement("a")
                ele.href = url
                ele.download = route.params.filename + "_ask_junctionseq/" + route.params.circ + `.${downloadType}`
                ele.click()
                urlObject.revokeObjectURL(url)
                loading.value = false
                ElMessage({
                    message: 'data has been downloaded.',
                    type: 'success',
                })
            }
        } catch (error:any) {
            loading.value = false
            ElMessage({
                message: error,
                type: 'error',
            })
        }
    }


    onBeforeMount(() => {
        getCircData()
        getRingData()
    })
</script>

<style scoped>
    pre {
        margin: 0;
    }

    :deep(.vue-office-pdf-wrapper) {
        background: white !important
    }

    .head {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .svg-wrapper {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
    }

    #plot-container svg {
        display: block;
        max-width: 100%;
        height: auto;
    }
</style>